#include <sys/shm.h>

#include "shm_com.h"

int main()
{
	int running = 1;
	void * shared_memory = (void*) 0;
	struct share_use_st * shared_stuff;
	char buffer[BUFSIZ];
	int shmid;

	shmid = shmget((key_t) 1234, sizeof (struct share_use_st), 0666 | IPC_CREAT);//创建共享内存
	if (shmid == -1 ) {
		fprintf(stderr,"Shmget Failed\n");
		exit (EXIT_FAILURE);
	}

	shared_memory = shmat(shmid, (void*)0, 0);//使用shmget得到的标识符来访问共享内存。成功返回一个共享内存的第一个字节的地址，失败返回-1。使用shared_memory来获取shmat的返回值，然后通过另一个结构体指针来访问它
	
	if (shared_memory == (void *)-1) {
		fprintf(stderr,"Shmat Failed\n");
		exit(EXIT_FAILURE);
	}
	printf("Memory Attached at %lX\n",(intptr_t) shared_memory);
	shared_stuff = (struct share_use_st * ) shared_memory;
	while (running ) {
	/*	while (shared_stuff->written_by_you == 1 ) {
			sleep(1);
			printf("Waiting for client...\n");
		}
	*/	printf("Enter some text: ");
		fgets(buffer,BUFSIZ,stdin);

		strncpy(shared_stuff->some_text, buffer ,TEXT_SZ);//操作共享内存中数据结构的数据
		shared_stuff->written_by_you = 1;

		if (strncmp(buffer,"end",3) == 0) {
			running = 0;
		}


	}
	
	if (shmdt(shared_memory ) == -1 ) {
		fprintf(stderr,"Shmdt Failed\n");
		exit(EXIT_FAILURE);
	}//与共享内存分离

	printf("Server Bye bye\n");
	exit(EXIT_SUCCESS);
}
